package cumeo89.chii.client.ui;

import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.UIObject;

public class ExtendedScrollPanel extends ScrollPanel {

	/**
	 * Ensures that the specified item is visible, by adjusting the panel's
	 * scroll position.
	 * 
	 * @param item
	 *            the item whose visibility is to be ensured
	 */
	public void ensureVisible(UIObject item) {
		Element scroll = getElement();
		Element element = item.getElement();
		ensureVisibleImpl(scroll, element);
	}

	/*
	 * modify to scroll only if element is not visible
	 */
	private native void ensureVisibleImpl(Element scroll, Element e) /*-{
		if (!e)
		  return; 

		var item = e;
		var realOffset = 0;
		while (item && (item != scroll)) {
		  realOffset += item.offsetTop;
		  item = item.offsetParent;
		}

		if (realOffset < scroll.scrollTop) {
			scroll.scrollTop = realOffset - 2;
		}
		if (realOffset + e.offsetHeight > scroll.scrollTop + scroll.offsetHeight) {
			scroll.scrollTop = realOffset + e.offsetHeight - scroll.offsetHeight + 2;
		}
	}-*/;

}
